package com.shan.common.db;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

/**
 * Author: shanzheng <br/>
 * Description: 动态数据源（数据源切换）<br/>
 * Date： 20:00 2017/8/7.<br/>
 * Modified By: <br/>
 */
public class DynamicDataSource extends AbstractRoutingDataSource {

    private final static Logger logger = LoggerFactory.getLogger(DynamicDataSource.class);

    private final static ThreadLocal<String> contextHolder = new ThreadLocal<>();

    /*
    该类充当了DataSource的路由中介,
    能有在运行时, 根据某种key值来动态切换到真正的DataSource上。
    */
    @Override
    protected Object determineCurrentLookupKey() {
        String dataSource = getDataSource();
        logger.info("当前操作使用的数据源：{}", dataSource);
        return dataSource;
    }

    /**
     * Description: 设置数据源<br/>
     * Param: [datasource：数据] <br/>
     * Author:shanzheng <br/>
     * Date: 9:09 2017/8/8 <br/>
     * Return: void <br/>
     */
    public static void setDataSource(String datasource) {
        contextHolder.set(datasource);
    }

    /**
     * Description: 获取数据源<br/>
     * Param: [] <br/>
     * Author:shanzheng <br/>
     * Date: 9:24 2017/8/8 <br/>
     * Return: java.lang.String <br/>
     */

    public static String getDataSource() {
        String dataSource = contextHolder.get();
        //如果没有指定数据源，使用默认数据
        if (dataSource == null) {
            DynamicDataSource.setDataSource(DataSourceEnum.MASTER.getDefault());
        }
        return contextHolder.get();
    }

    /**
     * Description: 清除数据源<br/>
     * Param: [] <br/>
     * Author:shanzheng <br/>
     * Date: 9:28 2017/8/8 <br/>
     * Return: void <br/>
     */
    public static void clearDataSource() {
        contextHolder.remove();
    }

}
